#!/usr/bin/perl -w
use strict;

my $parse_tmp_file_path_string = "bwa_sam_tmp";
my $parse_sam_exe_string = "bwa_sam_sam_exe";
my $parse_fa_file_string = "bwa_sam_fa_file";
my $parse_hadoop_exe_string = "bwa_sam_hadoop";

my $fa_file_path;
my $tmp_file_path;
my $sam_exe;
my $hadoop_exe;

my $config_fn="/tmp/config";
my $config_fh;

open $config_fh,$config_fn or die("Can not open at $!\n");
my @contents = <$config_fh>;
foreach my $line(@contents){
        chomp($line);

        if($line =~ /($parse_fa_file_string)(=)(.*)/){
                $fa_file_path = $3;
                print STDERR "fa_file_path: $fa_file_path\n";
        }
        elsif($line =~ /($parse_tmp_file_path_string)(=)(.*)/){
                $tmp_file_path = $3;
                print STDERR "tmp_file_path: $tmp_file_path\n";
        }
        elsif($line =~ /($parse_sam_exe_string)(=)(.*)/){
                $sam_exe = $3;
                print STDERR "sam_exe: $sam_exe\n";
        }
	elsif($line =~ /($parse_hadoop_exe_string)(=)(.*)/){
                $hadoop_exe = $3;
                print STDERR "hadoop_exe: $hadoop_exe\n";
        }
}
close $config_fh;

my $samtools = $sam_exe;
my $path = $tmp_file_path;
my $super_bam_name = "super.bam";
my $FA_path = $fa_file_path;
my $pileup_name = "pileup.txt";
my $args;
#my $counter = 0;
my $bam_ext = ".bam";

my $local_args;
my $hadoop=$hadoop_exe;
my $local_bam_file;

while(<>){
	chomp($_);
	#print $_;
	print STDERR "[adbg] 1.$_ [adbg]\n";
	$args .= $_;
	print STDERR "[adbg] 2.$args [adbg]\n";
	#print "[adbg] $args [adbg]\n";
	my $bam_file = $_;
	print STDERR "[adbg]1. $bam_file [adbg]\n";
	$bam_file =~ /(.*)(\/)(.*)/;
        my $local_bam_file = $3;
	print STDERR "[adbg]2. $hadoop fs -get $bam_file $path$local_bam_file [adbg]\n";
        system("$hadoop fs -get $bam_file $path$local_bam_file") == 0 or die "could not execute at $!";
	$local_args .= $path.$local_bam_file." ";
	print STDERR "[adbg]3. local_args: $local_args [adbg]\n";
=cut
	#my $url_f = $url.$_;
	my @bam_files = split(' ',$args);
	#print STDERR "<adbg> $url_f <adbg>\n";
	foreach my $bam_file(@bam_files){
		my $url_f = $bam_file;
		print STDERR "[adbg] $url_f [adbg]\n";	
		$bam_file =~ /(.*)(\/)(.*)/;
		$local_bam_file = $3;
		print STDERR "$hadoop fs -get $url_f $path$local_bam_file\n";
		system("$hadoop fs -get $url_f $path$local_bam_file") == 0 or die "could not execute at $!";
		$local_args .= $path.$local_bam_file." ";
	}
=cut
}
print STDERR "[adbg] args: $local_args [adbg]\n";
print STDERR "[adbg] merge $samtools merge $path$super_bam_name $local_args\n";
system("$samtools merge $path$super_bam_name $local_args") == 0 or die "could not execute at $!";
print STDERR "[adbg] pileup $samtools pileup -f $FA_path $path$super_bam_name > $path.$pileup_name\n";
system("$samtools pileup -f $FA_path $path$super_bam_name > $path$pileup_name") == 0 or die "could not execute at $!";
